package com.ojoin.trade.bpm.web.controller;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ojoin.trade.bpm.web.domain.Bpm;
import com.ojoin.trade.bpm.web.domain.ProcessDefinitionVO;
import com.ojoin.trade.bpm.web.service.BpmTaskService;
import com.ojoin.trade.bpm.web.support.BpmUtils;
import com.ojoin.trade.bpm.web.support.Page;
import com.ojoin.trade.common.web.controller.SimpleBaseController;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.Result.Status;
import com.ojoin.trade.common.web.service.impl.UserUtils;

/**
 * 流程个人任务相关Controller
 */
@Controller
@RequestMapping(value = "/bpm/task")
public class BpmTaskController extends SimpleBaseController {

	@Autowired
	private BpmTaskService bpmTaskService;
	
	/**
	 * 获取待办列表
	 * @param procDefKey 流程定义标识
	 * @return
	 */
	@ResponseBody
	@RequestMapping("todo")
	public Result todoList(Bpm act) throws Exception {
		List<Bpm> list = bpmTaskService.todoList(act);
		return new Result(Status.OK,list);
	}
	
	/**
	 * 获取已办任务
	 * @param page
	 * @param procDefKey 流程定义标识
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "done")
	public Result doneList(Bpm bpm, Pageable fpage) throws Exception {
		Page<Bpm> page = new Page<Bpm>();
		page.setPageNo(fpage.getPageNumber());
		page = bpmTaskService.historicList(page, bpm);
		return new Result(Status.OK,page.convert());
	}

	/**
	 * 获取流转历史列表
	 * @param procInsId 流程实例
	 * @param startBpm 开始活动节点名称
	 * @param endBpm 结束活动节点名称
	 */
	@ResponseBody
	@RequestMapping(value = "histoicFlow")
	public Result histoicFlow(Bpm bpm, String startBpm, String endBpm){
		if (StringUtils.isNotBlank(bpm.getProcInsId())){
			List<Bpm> histoicFlowList = bpmTaskService.histoicFlowList(bpm.getProcInsId(), startBpm, endBpm);
			return new Result(Status.OK,histoicFlowList);
		}
		return new Result(Status.OK,"");
	}
	
	/**
	 * 获取流程列表
	 * @param category 流程分类
	 */
	@ResponseBody
	@RequestMapping(value = "process")
	public Result processList(String category) {
	    Page<ProcessDefinitionVO> page = new Page<ProcessDefinitionVO>();
	    page = bpmTaskService.processList(page, category);
		return new Result(Status.OK,page.convert());
	}
	
	/**
	 * 获取流程表单
	 * @param taskId	任务ID
	 * @param taskName	任务名称
	 * @param taskDefKey 任务环节标识
	 * @param procInsId 流程实例ID
	 * @param procDefId 流程定义ID
	 */
	@RequestMapping(value = "form")
	public String form(Bpm act, HttpServletRequest request, Model model){
		
		// 获取流程XML上的表单KEY
		String formKey = bpmTaskService.getFormKey(act.getProcDefId(), act.getTaskDefKey());

		// 获取流程实例对象
		if (act.getProcInsId() != null){
			ProcessInstance procIns = bpmTaskService.getProcIns(act.getProcInsId());
			act.setProcIns(procIns);
			//流程结束
			if(null==procIns){
				act.setHistProcIns(bpmTaskService.getHistProcIns(act.getProcInsId()));
			}
		}
		
		return "redirect:" + BpmUtils.getFormUrl(formKey, act);
		
	}
	
	/**
	 * 启动流程
	 * @param procDefKey 流程定义KEY
	 * @param businessTable 业务表表名
	 * @param businessId	业务表编号
	 */
	@RequestMapping(value = "start")
	@ResponseBody
	public String start(Bpm bpm, String table, String id, Model model) throws Exception {
		bpmTaskService.startProcess(bpm.getProcDefKey(), bpm.getBusinessId(), bpm.getBusinessTable(), bpm.getTitle());
		return "true";
	}

	/**
	 * 签收任务
	 * @param taskId 任务ID
	 */
	@RequestMapping(value = "claim")
	@ResponseBody
	public Result claim(Bpm act) {
		String userId = UserUtils.getUser().getLoginName();//ObjectUtils.toString(UserUtils.getUser().getId());
		bpmTaskService.claim(act.getTaskId(), userId);
		return new Result(Status.OK,"签收成功");
	}
	
	/**
	 * 完成任务
	 * @param taskId 任务ID
	 * @param procInsId 流程实例ID，如果为空，则不保存任务提交意见
	 * @param comment 任务提交意见的内容
	 * @param vars 任务流程变量，如下
	 * 		vars.keys=flag,pass
	 * 		vars.values=1,true
	 * 		vars.types=S,B  @see com.ojoin.trade.bpm.web.support.PropertyType
	 */
	@RequestMapping(value = "complete")
	@ResponseBody
	public String complete(Bpm act) {
		bpmTaskService.complete(act.getTaskId(), act.getProcInsId(), act.getComment(), act.getVars().getVariableMap());
		return "true";
	}
	
	/**
	 * 读取带跟踪的图片
	 */
	@RequestMapping(value = "trace/photo/{procDefId}/{execId}")
	public void tracePhoto(@PathVariable("procDefId") String procDefId, @PathVariable("execId") String execId, HttpServletResponse response) throws Exception {
		InputStream imageStream = bpmTaskService.tracePhoto(procDefId, execId);
		
		// 输出资源内容到相应对象
		byte[] b = new byte[1024];
		int len;
		while ((len = imageStream.read(b, 0, 1024)) != -1) {
			response.getOutputStream().write(b, 0, len);
		}
	}
	
	/**
	 * 输出跟踪流程信息
	 * 
	 * @param processInstanceId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "trace/info/{proInsId}")
	public List<Map<String, Object>> traceInfo(@PathVariable("proInsId") String proInsId) throws Exception {
		List<Map<String, Object>> activityInfos = bpmTaskService.traceProcess(proInsId);
		return activityInfos;
	}

	
	/**
	 * 删除任务
	 * @param taskId 流程实例ID
	 * @param reason 删除原因
	 */
	@RequiresPermissions("act:process:edit")
	@ResponseBody
	@RequestMapping(value = "deleteTask")
	public Result deleteTask(String taskId, String reason, RedirectAttributes redirectAttributes) {
		Result ret=new Result();
		if (StringUtils.isBlank(reason)){
			ret.setMessage("请填写删除原因");
		}else{
			bpmTaskService.deleteTask(taskId, reason);
			ret.setMessage("删除任务成功，任务ID=" + taskId);
		}
		return ret;
	}
	
	/**
	 * 委派任务
	 * (源任务办理人，委派你办理完成后任务还是回归到指派者，事情是你做的，任务属于指派者的)
	 * @param taskId 任务ID
	 * @param userId 被委派人
	 */
	public void delegateTask(String taskId, String userId){
		bpmTaskService.delegateTask(taskId, userId);
	}
	
	/**
	 * 被委派人完成任务
	 * @param taskId 任务ID
	 */
	public void resolveTask(String taskId){
		bpmTaskService.resolveTask(taskId);
	}
}
